package cn.hnu.qq.server.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import cn.hnu.qq.entity.User;
import cn.hnu.qq.server.dao.UserDao;

@Transactional
public class UserDaoImpl  implements UserDao{
	
	@PersistenceContext

	private EntityManager manager;
	
	public User findById(Integer id) {
		return manager.find(User.class, id);
	}

	public User findByAcount(String acount) {
		String jpql = "SELECT u FROM User u WHERE u.acount = :acount";
		Query query = manager.createQuery(jpql);
		query.setParameter("acount", acount);
		List<User> list = query.getResultList();
		return (list.size() > 0 ? list.get(0) : null);
	}

	public Boolean isExist(String acount) {
		if(findByAcount(acount) != null){
			return true;
		}
		return false;
	}

	public Boolean isExist(Integer id) {
		if(findById(id) != null){
			return true;
		}
		return false;
	}

	public EntityManager getManager() {
		return manager;
	}

	public void setManager(EntityManager manager) {
		this.manager = manager;
	}

	public void save(User user) {
		manager.persist(user);
	}

	public void update(User user) {
		manager.merge(user);
	}

	public void addFriend(String user,String friend) {
		User _user = findByAcount(user);
		User _friend = findByAcount(friend);
		if(_user == null || _friend == null){
			return;
		}
		_user.addFriends(_friend);
		_friend.addFriends(_user);
		manager.merge(_user);
	}

	public boolean isFriend(String user, String friend) {
		User _user = findByAcount(user);
		if(_user == null){
			return false;
		}
		return _user.getFriends().contains(findByAcount(friend));
	}

	public int deleteFriend(String user, String friend) {
		User _user = findByAcount(user);
		User _friend = findByAcount(friend);
		_user.removeFriend(_friend);
		_friend.removeFriend(_user);
		manager.merge(_user);
		manager.merge(_friend);
		return 0;
	}
	
}
